package com.xintonghua.bussiness.ui;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.RadioGroup;

import com.alibaba.fastjson.JSONObject;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.vector.update_app.UpdateAppBean;
import com.vector.update_app.UpdateAppManager;
import com.vector.update_app.service.DownloadService;
import com.xintonghua.bussiness.BuildConfig;
import com.xintonghua.bussiness.R;
import com.xintonghua.bussiness.api.HttpCent;
import com.xintonghua.bussiness.base.BaseActivity;
import com.xintonghua.bussiness.bean.UpdateBea;
import com.xintonghua.bussiness.event.OnfreshEventBus;
import com.xintonghua.bussiness.ui.fragment.ClientFragment;
import com.xintonghua.bussiness.ui.fragment.CollegeFragment;
import com.xintonghua.bussiness.ui.fragment.DataCubeFragment;
import com.xintonghua.bussiness.ui.fragment.HomeFragment;
import com.xintonghua.bussiness.ui.fragment.MyFragment;
import com.xintonghua.bussiness.ui.home.SettlementActivity;
import com.xintonghua.bussiness.ui.view.CommonDialog;
import com.xintonghua.bussiness.util.HProgressDialogUtils;
import com.xintonghua.bussiness.util.ImageTools;
import com.xintonghua.bussiness.util.JsonUtil;
import com.xintonghua.bussiness.util.MyState;
import com.xintonghua.bussiness.util.UpdateAppHttpUtil;


import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener, CommonDialog.DialogClickListener {

    @BindView(R.id.rg_tab)
    RadioGroup rgTab;
    CommonDialog versionDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        HttpCent.getAuth();
        if (savedInstanceState == null) {
            HomeFragment homeFragment = new HomeFragment();
            DataCubeFragment dataCubeFragment = new DataCubeFragment();
            ClientFragment clientFragment = new ClientFragment();
            CollegeFragment collegeFragment = new CollegeFragment();
            MyFragment myFragment = new MyFragment();
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fl_wrap, myFragment, getString(R.string.me_page)).hide(myFragment)
                    .add(R.id.fl_wrap, collegeFragment, getString(R.string.college_page)).hide(collegeFragment)
                    .add(R.id.fl_wrap, clientFragment, getString(R.string.client_page)).hide(clientFragment)
                    .add(R.id.fl_wrap, dataCubeFragment, getString(R.string.cube_page)).hide(dataCubeFragment)
                    .add(R.id.fl_wrap, homeFragment, getString(R.string.main_page)).show(homeFragment)
                    .commit();
        }
        rgTab.setOnCheckedChangeListener(this);
        versionDialog = new CommonDialog(this);

        httpCent.update(this, MyState.requestOne);
        requestPermissions();

    }

    private void requestPermissions() {
        RxPermissions rxPermission = new RxPermissions(MainActivity.this);
        rxPermission.requestEach(
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.INTERNET,
                Manifest.permission.READ_CALENDAR,
                Manifest.permission.READ_CALL_LOG,
                Manifest.permission.READ_CONTACTS,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.READ_SMS,
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.CAMERA,
                Manifest.permission.CALL_PHONE,
                Manifest.permission.SEND_SMS)
                .subscribe(permission -> {
                    if (permission.granted) {
                    } else if (permission.shouldShowRequestPermissionRationale) {
                    } else {
                    }
                });

    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
        showFragment(checkedId);
    }

    public void showFragment(int resId) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        hideFragments(ft);

        switch (resId) {
            case R.id.rb_home:
                Fragment homeFragment = getSupportFragmentManager().findFragmentByTag(getString(R.string.main_page));
                if (homeFragment != null) {
                    ft.show(homeFragment);
                    EventBus.getDefault().post(new OnfreshEventBus());
                }
                break;
            case R.id.rb_cube:
                Fragment dataCubeFragment = getSupportFragmentManager().findFragmentByTag(getString(R.string.cube_page));
                if (dataCubeFragment != null) {
                    ft.show(dataCubeFragment);
                }
                break;
            case R.id.rb_client:
                Fragment clientFragment = getSupportFragmentManager().findFragmentByTag(getString(R.string.client_page));
                if (clientFragment != null) {
                    ft.show(clientFragment);
                }
                break;
            case R.id.rb_college:
                Fragment collectFragment = getSupportFragmentManager().findFragmentByTag(getString(R.string.college_page));
                if (collectFragment != null) {
                    ft.show(collectFragment);
                }
                break;

            case R.id.rb_me:
                Fragment myFragment = getSupportFragmentManager().findFragmentByTag(getString(R.string.me_page));
                if (myFragment != null) {
                    ft.show(myFragment);
                }
                break;
            default:
                break;
        }

        ft.commit();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == MyState.requestL3000 && resultCode == Activity.RESULT_OK) {
//            Log.i("aaa", "data+=====>" + data);
//            if (data != null) {
//                Log.i("aaa", "數據===》" + data.getExtras().getSerializable("data"));
//                List<Point> pointList = (List<Point>) data.getSerializableExtra("data");
//                int width = data.getIntExtra("width", 300);
//                int height = data.getIntExtra("height", 200);
//                Bitmap bmp = ChangeBitmap(pointList, width, height);
//                Log.i("aaa", "目前list大小===》" + pointList.size());
//                String bmp1filename = getApplicationContext().getFilesDir().getAbsolutePath() + "/" + bmp + System.currentTimeMillis();
//                ImageTools.savePhotoToSDCard(bmp, bmp1filename);
//
//                File file1 = new File(bmp1filename);
//
//                List<String> list = new ArrayList<>();
//                list.add(file1.getAbsolutePath());
////                ImageTools.loadImage(MainActivity.this, bmp1filename., this, MyState.requestFour);
//            }
        }
    }

    @Override
    public void dataBack(Object data, int order) {
        super.dataBack(data, order);
        try {
            switch (order) {
                case MyState.requestFour:
                    try {
//                        String datas = JsonUtil.getListString(data.toString());
//                        Submit(datas);
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.i("aaa", "错误");
                    }
                    break;
                case MyState.requestOne:
                    UpdateBea bean = JSONObject.parseObject((String) data, UpdateBea.class);
                    if (bean.getCode() > BuildConfig.VERSION_CODE) {
                        show(bean);
                    }

                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void Submit(String data) {


    }

    public Bitmap ChangeBitmap(List<Point> plist, int widths, int heights) {
        int width;
        int height;
        width = widths;
        height = heights;

        Log.i("aaa", "canvas-----> width====>" + width + "//height===>" + height);
        //创建一个bitmap
        Bitmap newb = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);// 创建一个新的和SRC长度宽度一样的位图
        //将该图片作为画布\
        Canvas canvas = new Canvas(newb);

        Paint paint = new Paint();
        paint.setColor(Color.WHITE);
        canvas.drawRect(new Rect(0, 0, width, height), paint);
        paint.setColor(Color.RED);
        paint.setAntiAlias(true);
        paint.setStrokeCap(Paint.Cap.ROUND);
        for (int i = 0; i < plist.size() - 1; i++) {
            if (plist.get(i).x > 0 && plist.get(i).y > 0 && plist.get(i + 1).x > 0 && plist.get(i + 1).y > 0)
                canvas.drawLine(plist.get(i).x, plist.get(i).y, plist.get(i + 1).x, plist.get(i + 1).y, paint);
        }
        // 保存
        canvas.save();
        // 存储
        canvas.restore();
        return newb;
    }


    // 当fragment已被实例化，就隐藏起来

    public void hideFragments(FragmentTransaction ft) {
        List<Fragment> mFragment = getSupportFragmentManager().getFragments();
        if (mFragment != null && mFragment.size() > 0) {
            for (Fragment fragment : mFragment) {
                ft.hide(fragment);
            }
        }
    }

    private void show(UpdateBea bean) {
        versionDialog.setDialogClickListener(this);
        versionDialog.setUrl(bean.getUrl());
        versionDialog.setOrder(1);
        versionDialog.setAlert(bean.getContent());
        versionDialog.setCancelButtonEnable(bean.getIsForce());
        versionDialog.setCancelable(false);
        versionDialog.setCanceledOnTouchOutside(false);
        versionDialog.show();
    }

    @Override
    public void dialogSure(int order, String url) {
        switch (order) {
            case 0:
                break;
            case 1:
                UpdateAppBean updateAppBean = new UpdateAppBean();
                updateAppBean.setApkFileUrl(url);
                String path = "";
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) || !Environment.isExternalStorageRemovable()) {
                    try {
                        path = getExternalCacheDir().getAbsolutePath();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (TextUtils.isEmpty(path)) {
                        path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
                    }
                } else {
                    path = getCacheDir().getAbsolutePath();
                }
                //设置apk 的保存路径
                updateAppBean.setTargetPath(path);
                //实现网络接口，只实现下载就可以
                updateAppBean.setHttpManager(new UpdateAppHttpUtil());
                UpdateAppManager.download(this, updateAppBean, new DownloadService.DownloadCallback() {
                    @Override
                    public void onStart() {
                        HProgressDialogUtils.showHorizontalProgressDialog(MainActivity.this, "下载进度", false);

                    }

                    @Override
                    public void onProgress(float progress, long totalSize) {
                        HProgressDialogUtils.setProgress(Math.round(progress * 100));

                    }

                    @Override
                    public void setMax(long totalSize) {
                    }

                    @Override
                    public boolean onFinish(File file) {
                        HProgressDialogUtils.cancel();
                        return true;
                    }

                    @Override
                    public void onError(String msg) {
                        HProgressDialogUtils.cancel();
                    }

                    @Override
                    public boolean onInstallAppAndAppOnForeground(File file) {
                        return false;
                    }
                });
                break;
        }
    }

    @Override
    public void dialogCancel() {

    }

}
